package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.Travelcontent;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.mapper.TravelcontentMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService{
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelcontentMapper travelcontentMapper;
    @Override
    public PageInfo query(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Travel> travels = travelMapper.selectForList(qo);
        return new PageInfo(travels);
    }

    @Override
    public Travel getTravelById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public Travelcontent getContentById(Long id) {
        return travelcontentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void changeState(Travel travel) {
        //更新发布日期
        if (Travel.STATUS_RELEASE == travel.getState()){
            travel.setReleaseTime(new Date());
        }
        travelMapper.changeState(travel);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        //编辑
        if (travel.getId() != null) {
            //编辑的同时.编辑游记内容
            travelMapper.updateByPrimaryKey(travel);
            Travelcontent travelcontent = travel.getTravelcontent();
            travelcontent.setId(travel.getId());
            travelcontentMapper.updateByPrimaryKey(travelcontent);
        }else{
            //新增先保存游记信息
            travelMapper.insert(travel);
            Travelcontent travelcontent = travel.getTravelcontent();
            travelcontent.setId(travel.getId());
            //再保存游记内容
            travelcontentMapper.insert(travelcontent);

        }
    }
}
